from decimal import Decimal
import re
from sqlalchemy import null, true,false
import ast #安全转换字符串为列表
from double_invoice_data import *#数据
import ast
import ast
import re
from invoice_result_dict_deal import *
# 双模型校验数据结果处理；

# -------------list_deal;


def listContainJudgeShort(l1, l2):
    """
    功能：以较短的长度为基准。存在包含关系的以大包含为准替代另一个值；
    逐个判断两个列表中是否存在包含关系，并返回结果;
    如果l1中存在l2中的元素，则将l2中的元素赋值给l1，否则将l1中的元素赋值给l2;
    优点：可处理："[]"形式；
    调用：
    l1 = "['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']"
    l2 = "['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']"
    l3, l4 = listContainJudgeL1(l1,l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    for a, b in zip(l1, l2):
        if a in b:
            l3.append(b)
            l4.append(b)
        elif b in a:
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    return l3, l4


def listContainJudgeL1(l1, l2):
    """
    功能：以l1长度为基准。存在包含关系的以大包含为准替代另一个值；
    以 l1 的长度为准，l2 不足的部分用 l1 对应位置的值填充。
    调用：
    l1 = ['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']
    l2 = ['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']
    l3, l4 = listContainJudgeL1(l1,l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    for i, a in enumerate(l1):
        if i<len(l2):
            if a in l2[i]:
                l3.append(l2[i])
                l4.append(l2[i])
            elif l2[i] in a:
                l3.append(a)
                l4.append(a)
            else:
                l3.append(a)
                l4.append(l2[i])
        else:#长度不足时，用l1的值填充
            l3.append(a)
            l4.append(a)
    return l3, l4

def listContainJudgeL2(l1, l2):
    """
    以 l2 的长度为准，l1 不足的部分用 l2 对应位置的值填充。
    逐个判断两个列表中对应位置的元素是否存在包含关系：
    调用：
    l1 = ['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']
    l2 = ['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']

    l3, l4 = listContainJudgeL2(l1, l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    # 确保 l1 长度与 l2 相同，不足部分用 l2 的值填充
    l1_adjusted = l1 + l2[len(l1):] if len(l1) < len(l2) else l1[:len(l2)]
    
    for a, b in zip(l1_adjusted, l2):
        if a in b:
            l3.append(b)
            l4.append(b)
        elif b in a:
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    return l3, l4


# 字符串标准化函数(中文括号替换为英文的)
def normalize_string(s):
    if not isinstance(s, str):
        s = str(s)
    s = (s.replace('（', '(')
            .replace('）', ')')
            .replace('【', '[')
            .replace('】', ']'))
    return re.sub(r'\s+', ' ', s).strip()
 
 
# 输入转换函数
def convert_input(obj):
    if isinstance(obj, str):
        try:
            lst = ast.literal_eval(obj.strip())
            return [normalize_string(x) for x in lst] if isinstance(lst, list) else [normalize_string(lst)]
        except:
            return [normalize_string(obj)]
    elif isinstance(obj, list):
        return [normalize_string(x) for x in obj]
    return [normalize_string(obj)]   


def listContainJudgeShort(l1, l2):
    """
    功能：以较短的长度为基准。存在包含关系的以大包含为准替代另一个值；
    逐个判断两个列表中是否存在包含关系，并返回结果;
    如果l1中存在l2中的元素，则将l2中的元素赋值给l1，否则将l1中的元素赋值给l2;
    优点：可处理："[]"形式；
    调用：
    l1 = "['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']"
    l2 = "['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']"
    l3, l4 = listContainJudgeL1(l1,l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    for a, b in zip(l1, l2):
        if a in b:
            l3.append(b)
            l4.append(b)
        elif b in a:
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    return l3, l4


def listContainJudgeL1(l1, l2):
    """
    功能：以l1长度为基准。存在包含关系的以大包含为准替代另一个值；
    以 l1 的长度为准，l2 不足的部分用 l1 对应位置的值填充。
    调用：
    l1 = ['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']
    l2 = ['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']
    l3, l4 = listContainJudgeL1(l1,l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    for i, a in enumerate(l1):
        if i<len(l2):
            if a in l2[i]:
                l3.append(l2[i])
                l4.append(l2[i])
            elif l2[i] in a:
                l3.append(a)
                l4.append(a)
            else:
                l3.append(a)
                l4.append(l2[i])
        else:#长度不足时，用l1的值填充
            l3.append(a)
            l4.append(a)
    return l3, l4

def listContainJudgeL2(l1, l2):
    """
    以 l2 的长度为准，l1 不足的部分用 l2 对应位置的值填充。
    逐个判断两个列表中对应位置的元素是否存在包含关系：
    调用：
    l1 = ['2025.04.01-202', '', '2025.02.01-202', '2025.03.01-202']
    l2 = ['2025.01.01-202', '2025', '2025.02.01-202', '2025.03.01-202', '2025.02.01-202', '2025.03.01-202']

    l3, l4 = listContainJudgeL2(l1, l2)
    print("l3:", l3)
    print("l4:", l4)
    """
    l3 = []
    l4 = []
    # 确保 l1 长度与 l2 相同，不足部分用 l2 的值填充
    l1_adjusted = l1 + l2[len(l1):] if len(l1) < len(l2) else l1[:len(l2)]
    
    for a, b in zip(l1_adjusted, l2):
        if a in b:
            l3.append(b)
            l4.append(b)
        elif b in a:
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    return l3, l4


def listSafeContainJudgeL1(l1, l2):
    """
    增强版安全比较函数（带字符串标准化处理）
    
    参数：
        l1, l2: 可以是列表，或字符串形式的列表（如 "['a', 'b']"）
    
    返回：
        l3, l4: 处理后的两个列表
        
    功能说明：
        1. 自动识别并转换输入格式
        2. 字符串标准化处理（统一括号、去除空白）
        3. 以l1长度为准，l2不足时用l1的值填充
        4. 智能元素比较（包含关系判断）
        调用：
# model: ['ZH-283(不含软件及D5F接口)']", "['Y-TZZJ-256M', 'ZHZJ-639', 'ZC/DY/8-12V', 'ZH-283']"]
l1 ="['Y-TZZJ-256M', 'ZHZJ-639(不含软件)', 'ZC/DY/8-12V', 'ZH-283(不含软件及D5F接口)']"
l2= "['Y-TZZJ-256M', 'ZHZJ-639', 'ZC/DY/8-12V', 'ZH-283']"
l3,l4=listSafeContainJudgeL1(l1,l2)
# l3, l4 = listSafeContainJudge(l1, l2, "left")
print("l3:", l3)
print("l4:", l4)
    """
    # 处理输入数据
    l1 = convert_input(l1)
    l2 = convert_input(l2)
    
    # 执行比较逻辑
    l3, l4 = [], []
    for i, a in enumerate(l1):
        b = l2[i] if i < len(l2) else a
        if a in b and a!="":
            l3.append(b)
            l4.append(b)
        elif b in a and b!="":
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    
    return l3, l4


def listSafeContainJudgeL2(l1, l2):
    """
    增强版函数：智能处理输入（支持字符串列表和直接列表），以l2长度为基准比较
    
    参数：
        l1, l2: 可以是列表，或字符串形式的列表（如 "['a', 'b']"）
    
    返回：
        l3, l4: 处理后的两个列表
        
    功能说明：
        1. 自动识别字符串形式的列表并转换
        2. 以l2长度为准，l1不足时用l2的值填充
        3. 元素比较规则：
           - 若l1[i]包含于l2[i]，取l2[i]
           - 若l2[i]包含于l1[i]，取l1[i]
           - 否则保持各自原值
    """
    # 智能转换输入为列表（内部函数）
    def convert_input(obj):
        if isinstance(obj, str):
            try:
                return ast.literal_eval(obj.strip())
            except (ValueError, SyntaxError):
                return [obj]  # 如果不是合法列表字符串，当作单元素列表
        elif isinstance(obj, list):
            return obj
        else:
            return [str(obj)]  # 其他类型转为单元素列表

    # 转换输入数据
    l1 = convert_input(l1)
    l2 = convert_input(l2)
    
    # 调整l1长度与l2一致（不足补l2的值，超出则截断）
    l1_adjusted = l1 + l2[len(l1):] if len(l1) < len(l2) else l1[:len(l2)]
    
    l3, l4 = [], []
    for a, b in zip(l1_adjusted, l2):
        if a in b and a!="":
            l3.append(b)
            l4.append(b)
        elif b in a and b!="":
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    
    return l3, l4


def listSafeContainJudge(l1, l2, base="left"):
    """
    通用安全比较函数 - 可根据参数选择以左侧(l1)或右侧(l2)列表为基准
    
    参数：
        l1, l2: 可以是列表，或字符串形式的列表（如 "['a', 'b']"）
        base: 基准选择，可选值：
              - "left" 或 "l1": 以l1长度为基准（默认）
              - "right" 或 "l2": 以l2长度为基准
              - "short": 以较短列表为基准
              - "long": 以较长列表为基准
    
    返回：
        l3, l4: 处理后的两个列表
        
    功能说明：
        1. 自动识别并转换输入格式
        2. 字符串标准化处理（统一括号、去除空白）
        3. 根据base参数选择基准列表
        4. 智能元素比较（包含关系判断）
        
    调用示例1：
        l1 = "['ZHZJ-639(不含软件)', 'Y-TZZJ-256M']"
        l2 = "['ZHJZJ-639(不含软件)', 'Y-TZZJ-256M', '额外元素']"
        
        # 以l1为基准
        l3, l4 = listSafeContainJudge(l1, l2, "left")
        
        # 以l2为基准
        l3, l4 = listSafeContainJudge(l1, l2, "right")
        
        # 以较短列表为基准
        l3, l4 = listSafeContainJudge(l1, l2, "short")
    调用示例2：
    l1 = ['ZHZJ-639(不含软件)', 'Y-TZZJ-256M',"1"]
    l2 = ['ZHJZJ-639(不含软件)', 'Y-TZZJ-256M']
    l3, l4 = listSafeContainJudge(l1, l2, "right")
    print("l3:", l3)
    print("l4:", l4)
    """

    # 处理输入数据
    l1_normalized = convert_input(l1)
    l2_normalized = convert_input(l2)
    
    # 确定基准列表
    base = base.lower()
    if base in ["right", "l2", "r"]:
        # 以l2为基准
        base_list = l2_normalized
        other_list = l1_normalized
        # 调整l1长度与l2一致
        l1_adjusted = l1_normalized + l2_normalized[len(l1_normalized):] if len(l1_normalized) < len(l2_normalized) else l1_normalized[:len(l2_normalized)]
        l2_adjusted = l2_normalized
    elif base in ["short", "s"]:
        # 以较短列表为基准
        if len(l1_normalized) <= len(l2_normalized):
            base_list = l1_normalized
            other_list = l2_normalized
            l1_adjusted = l1_normalized
            l2_adjusted = l2_normalized[:len(l1_normalized)]
        else:
            base_list = l2_normalized
            other_list = l1_normalized
            l1_adjusted = l1_normalized[:len(l2_normalized)]
            l2_adjusted = l2_normalized
    elif base in ["long", "l"]:
        # 以较长列表为基准
        if len(l1_normalized) >= len(l2_normalized):
            base_list = l1_normalized
            other_list = l2_normalized
            l1_adjusted = l1_normalized
            l2_adjusted = l2_normalized + l1_normalized[len(l2_normalized):]
        else:
            base_list = l2_normalized
            other_list = l1_normalized
            l1_adjusted = l1_normalized + l2_normalized[len(l1_normalized):]
            l2_adjusted = l2_normalized
    else:
        # 默认以l1为基准
        base_list = l1_normalized
        other_list = l2_normalized
        l1_adjusted = l1_normalized
        l2_adjusted = l2_normalized[:len(l1_normalized)] if len(l2_normalized) > len(l1_normalized) else l2_normalized + [l1_normalized[i] for i in range(len(l2_normalized), len(l1_normalized))]
    
    # 执行比较逻辑
    l3, l4 = [], []
    for a, b in zip(l1_adjusted, l2_adjusted):
        if a in b:
            l3.append(b)
            l4.append(b)
        elif b in a:
            l3.append(a)
            l4.append(a)
        else:
            l3.append(a)
            l4.append(b)
    
    return l3, l4

# -------------list_deal---end;

def convert_to_chinese_amount(num):
    """
    将阿拉伯数字转换为中文大写数字（修正版）
    :param num: 数字，可以是整数或浮点数
    :return: 中文大写数字字符串
    """
    # 定义数字对应的大写
    digit_map = {
        '0': '零',
        '1': '壹',
        '2': '贰',
        '3': '叁',
        '4': '肆',
        '5': '伍',
        '6': '陆',
        '7': '柒',
        '8': '捌',
        '9': '玖'
    }
    
    # 定义单位
    unit_map = [
        ('', '拾', '佰', '仟'),       # 个位
        ('万', '拾万', '佰万', '仟万'), # 万位
        ('亿', '拾亿', '佰亿', '仟亿'), # 亿位
        ('兆', '拾兆', '佰兆', '仟兆')  # 兆位
    ]
    
    # 处理小数部分
    decimal_units = ['角', '分']
    
    # 将数字转换为字符串，处理正负
    if not isinstance(num, (int, float)):
        raise ValueError("输入必须是数字")
    
    is_negative = False
    if num < 0:
        is_negative = True
        num = abs(num)
    
    num_str = format(num, '.2f')  # 格式化为两位小数
    
    # 分离整数和小数部分
    integer_part, decimal_part = num_str.split('.')
    
    # 处理整数部分
    def convert_integer_part(integer_str):
        if integer_str == '0':
            return ['零']
        
        result = []
        length = len(integer_str)
        
        # 分组处理，每4位一组
        groups = []
        while integer_str:
            groups.append(integer_str[-4:])
            integer_str = integer_str[:-4]
        groups.reverse()
        
        for i, group in enumerate(groups):
            group = group.lstrip('0')
            if not group:  # 全零组
                # 检查是否需要添加"零"或单位
                if i < len(groups) - 1 and any(c != '0' for c in groups[i+1]):
                    result.append('零')
                continue
            
            level = len(groups) - i - 1
            for j, digit in enumerate(group):
                if digit == '0':
                    # 处理连续的零，只保留一个
                    if j < len(group) - 1 and group[j+1] != '0':
                        result.append('零')
                else:
                    result.append(digit_map[digit])
                    pos = len(group) - j - 1
                    if pos > 0:
                        result.append(unit_map[0][pos])
            
            # 添加级单位（万、亿、兆）
            if level > 0 and any(c != '0' for c in group):
                result.append(unit_map[level][0])
        
        return result
    
    integer_chinese = convert_integer_part(integer_part)
    
    # 处理小数部分
    decimal_chinese = []
    if decimal_part != '00':
        for i, digit in enumerate(decimal_part[:2]):  # 只处理两位小数
            if digit != '0':
                decimal_chinese.append(digit_map[digit])
                if i < len(decimal_units):
                    decimal_chinese.append(decimal_units[i])
    
    # 组合结果
    result = []
    if is_negative:
        result.append('(负数)')
    
    if integer_chinese:
        result.extend(integer_chinese)
        result.append('圆')
    
    if decimal_chinese:
        result.extend(decimal_chinese)
    else:
        if integer_chinese and integer_chinese != ['零']:
            result.append('整')
    
    # 特殊情况处理：零元
    if integer_chinese == ['零'] and not decimal_chinese:
        return '零元整'
    
    return ''.join(result)


def is_unit(value):
    """判断给定的值是否为单位;单位可以为空值"""
    # units中括号中都用英文的；
    units = {
        '瓶', '袋', '个', '根', '次', '条', '把', '套', '台', '项',
        'KG', '包', '组', '元', '1', '份', '只', '卷', '升', '天',
        '期', '间', '桶', '单', '箱', '盒', '度', '件', '提', '斤',
        '付', '块', '桌', '笔', '平方米', '张', '罐', '批', '片', 
        '千克', '月',"","无","千瓦时","千瓦","千瓦时(度)"
    }
    value=normalize_string(value)
    return str(value) in units

def test_validate_and_correct_invoice_dict_field_model_unit():
    """
    测试验证并修正发票字典：
    """
    # 测试用例
    # test_cases = [
    #     {'model': '项', 'unit': '项'},      # 应该被修正（model → ''）
    #     {'model': '瓶', 'unit': '瓶'},      # 应该被修正（model → ''）
    #     {'model': '个', 'unit': '个'},      # 应该被修正（model → ''）
    #     {'model': '台', 'unit': '台'},      # 应该被修正（model → ''）
    #     {'model': 'ABC', 'unit': 'ABC'},    # 不修正（ABC 不是单位）
    #     {'model': '123', 'unit': '123'},    # 不修正（123 不是单位）
    #     {'model': '千克', 'unit': '千克'},  # 应该被修正（model → ''）
    #     {'model': '电脑', 'unit': '台'},    # 不修正（model ≠ unit）
    #     {'model': '1', 'unit': '1'},        # 应该被修正（model → ''，因为 '1' 是单位）
    #     {'model': '箱', 'unit': ''},        # 不修正（unit 为空）
    #     {'model': '个', 'unit': None},      # 不修正（unit 为 None）
    # ]

        # 示例使用
    input_data = {
        'model': "['项']", 
        'unit': "['项']",
        # 其他字段...
    }
    corrected_data = validate_and_correct_invoice_dict_field_model_unit(input_data)
    print(corrected_data)


def validate_and_correct_invoice_dict_field_model_unit(invoice_dict):
    """
    功能：model字段处理，model字段不应该等于单位，如果等于则置空；
    验证并修正发票字典：
    - 如果 `model` 值等于 `unit` 的值，且 `unit` 不为空，且 `model` 是单位，则将 `model` 置空
    处理格式如：
    {'model': "['项']", 'unit': "['项']"} → {'model': "['']", 'unit': "['项']"}
    """
    if not isinstance(invoice_dict, dict):
        raise ValueError("输入必须是一个字典")
    
    # 使用深度复制确保不会修改原始数据
    import copy
    result_dict = copy.deepcopy(invoice_dict)
    
    if 'model' in result_dict and 'unit' in result_dict:
        try:
            # 将字符串形式的列表转换为实际列表
            model_value = ast.literal_eval(result_dict['model']) if isinstance(result_dict['model'], str) else result_dict['model']
            unit_value = ast.literal_eval(result_dict['unit']) if isinstance(result_dict['unit'], str) else result_dict['unit']
            
            # 确保转换后是列表类型
            if isinstance(model_value, list) and isinstance(unit_value, list):
                if len(model_value) == len(unit_value):
                    new_model = []
                    for m, u in zip(model_value, unit_value):
                        if u and is_unit(m) and str(m).strip() == str(u).strip():
                            new_model.append('')
                        else:
                            new_model.append(m)
                    
                    # 将结果转换回字符串形式的列表
                    result_dict['model'] = str(new_model)
        except (ValueError, SyntaxError):
            # 如果转换失败，保持原样
            pass
    
    return result_dict

def validate_and_correct_invoice_dict(invoice_data:dict)->tuple:
    """
    验证并修正单个发票字典数据，确保数据的一致性和有效性。
    返回:
        tuple: 包含四个元素的元组:
            1. dict: 修正后的发票数据字典
            2. dict: 修改记录字典，格式为 {"key": ["value1-修改前", "value2-修改后"]}，记录从输入到返回值的变化
            3. bool: 是否满足基准(meetVerifyBaseline)，如果各字段和=totalAmount或各字段和=totalSmall-totalTax，则为True
            4. dict: 分项验证结果字典，包含以下键值对：
                - totalPriceAndTotalAmountVerify: 各字段和是否等于totalAmount
                - taxAmountAndTotalTaxVerify: taxAmount总和是否等于totalTax
                - totalAmountAndTotalSmallVerify: totalAmount+totalTax是否等于totalSmall
                （未成）
                # - onePagesubtotalAmount:各字段和不等于totalAmount时,判断各字段和是否等于subtotalAmount
                # - onePagesubtotalTax:taxAmount总和不等于totalTax时，判断taxAmount总和是否等于subtotalTax
    
    
    原理-基准：
    【（1）各字段和为第1基准：检查各分项金额之和是否等于总金额；
    （2）totalAmount第2基准：各字段首先与totalAmount进行验证，确保分项金额之和等于总金额；
    （3）totalSmall-totalTax第3基准：如果totalAmount与各字段计算的值不一致，则与totalSmall-totalTax进行验证，
    如果totalSmall-totalTax与totalAmount的值一致，则将totalSmall-totalTax的值赋给totalAmount；
    （4）totalSmall修正第4基准：如果totalPrice总和等于totalAmount，且taxAmount总和等于totalTax，
    但totalAmount+totalTax不等于totalSmall，则将totalSmall修正为totalAmount+totalTax的值。】
    （5）subtotalAmount第5基准：前面都不符合时，subtotalAmount要存在且有值，判断各字段和是否与subtotalAmount相等，
    
    
    
    验证并修正发票处理思路：
    [
        1）数据预处理
        首先复制输入的发票数据，以避免修改原始数据
        将字符串形式的列表转换为真正的Python列表，方便后续处理
        确保所有列表字段存在，如果不存在则创建空列表
        确保所有列表字段的元素个数相同
        去除特定键值中的￥符号，例如totalSmall、totalBig、totalAmount、totalTax、totalPrice
        
        2）totalPrice验证与修正（需求1）
        计算totalPrice的总和，与totalAmount进行比较
        如果不相等，分别尝试number、unitPrice和taxAmount的总和是否等于totalAmount
        如果某个字段的总和等于totalAmount，则将该字段的值赋给totalPrice
        如果没有任何字段的总和等于totalAmount，则尝试与totalSmall-totalTax进行匹配，如果匹配成功则更新totalAmount的值
        
        3）taxAmount验证与修正（需求2）
        对每个项目，根据totalPrice和taxRate计算正确的taxAmount值
        将计算得到的值赋给taxAmount
        
        4）unit验证（需求3）
        验证单位unit，不是单位，则置空；
        
        5）unitPrice和number验证（需求4）
        检查unitPrice乘以number是否等于totalPrice
        如果unitPrice*number不等于totalPrice，在原值后添加(随机三个字母)标记，而不是置空；
        如果number为空，将unitPrice也置为空
        如果unitPrice完全等于totalPrice，且number全为1，且unit为空，则将unitPrice和number均置空
        如果unitPrice=totalPrice且unit或unitPrice为空，则将number置为空
        如果number=totalPrice且unit或unitPrice为空，则将number置空
        
        6）处理空元素
        如果totalPrice检验符合totalAmount，且totalPrice的最右边包含空元素，则将空元素截断
        
        7）no字段处理
        如果no字段的值与invoiceNumber字段相同或是其子串，则将no字段置为空
        
        8）数据验证基准检查
        验证totalPrice总和是否等于totalAmount
        验证taxAmount总和是否等于totalTax
        验证totalAmount+totalTax是否等于totalSmall
        如果totalSmall-totalTax与totalPrice总和一致，也视为满足基准
        
        9）大写金额处理
        如果totalAmount+totalTax=totalSmall验证通过，则将totalSmall转为大写赋值给totalBig
        
        10）数据后处理
        最后将所有列表字段转回字符串格式，保持与原始数据格式一致
        
        11）第4基准：totalSmall修正
        如果totalPrice总和等于totalAmount且taxAmount总和等于totalTax，但totalAmount+totalTax不等于totalSmall，
        则修正totalSmall为totalAmount+totalTax的值，并更新totalBig
        
        12）model字段处理(list的要转为str)：
        功能：model字段处理，model字段不应该等于unit的单位（用函数判断是否为单位），如果等于则置空；validate_and_correct_invoice_dict_field_model_unit
        
        13）totalBig字段处理：
        功能：totalBig字段处理，如果原始totalBig包含"整"且转换后totalBig不包含"整"，则追加上；
    ]
    
    参数:
        invoice_data (dict): 包含发票信息的字典，预期包含以下字段：
            - totalAmount: 不含税金额总计
            - totalTax: 税额总计
            - totalSmall: 价税合计（小写金额）
            - totalBig: 价税合计（大写金额）
            - tradeName: 商品名称列表
            - model: 规格型号列表
            - unit: 单位列表
            - number: 数量列表
            - unitPrice: 单价列表
            - totalPrice: 金额列表（不含税）
            - taxRate: 税率列表
            - taxAmount: 税额列表
            - invoiceNumber: 发票号码
            - no: 订单号或其他编号
    

    """
    # 使用深度复制确保不会修改原始数据，包括嵌套的列表和字典
    import copy
    invoice = copy.deepcopy(invoice_data)
    
    # 创建修改记录字典
    modifications = {}
    
    # 创建满足基准标志
    meetVerifyBaseline = False
    
    # 创建分项验证结果字典
    item_verify_result = {
        "totalPriceAndTotalAmountVerify": False,
        "taxAmountAndTotalTaxVerify": False,
        "totalAmountAndTotalSmallVerify": False,
    }
    
    # 去除特定键值中的￥符号
    money_fields = ['totalAmount', 'totalTax', 'subtotalAmount', 'subtotalTax', 'totalBig', 'totalSmall']
    for field in money_fields:
        if field in invoice and invoice[field] and isinstance(invoice[field], str):
            original_value = invoice[field]
            # 去除￥符号
            cleaned_value = original_value.replace('￥', '')
            if original_value != cleaned_value:
                invoice[field] = cleaned_value
                # 记录修改
                if field not in modifications:
                    modifications[field] = [original_value, cleaned_value]
    
    # 定义需要处理的列表字段
    list_fields = ['tradeName', 'model', 'unit', 'number', 'unitPrice', 'totalPrice', 'taxRate', 'taxAmount']
    
    # 确保所有列表字段存在，如果不存在则添加空值
    for field in list_fields:
        if field not in invoice:
            invoice[field] = "[]"
    
    # 将字符串格式的列表转换为真正的Python列表
    for field in list_fields:
        if isinstance(invoice[field], str) and invoice[field].startswith('[') and invoice[field].endswith(']'):
            # 移除字符串中的引号和括号，然后分割
            cleaned = invoice[field].replace("'", "").replace("[", "").replace("]", "")
            if cleaned:
                invoice[field] = cleaned.split(', ')
            else:
                invoice[field] = []
        elif not isinstance(invoice[field], list):
            invoice[field] = []
    
    # 找出所有非空列表中的最大长度，用于统一长度
    max_length = 0
    for field in list_fields:
        if len(invoice[field]) > max_length:
            max_length = len(invoice[field])
    
    # 如果所有列表都为空，设置默认长度为1
    if max_length == 0:
        max_length = 1
    
    # 统一所有列表的长度
    for field in list_fields:
        # 如果列表为空，添加一个空元素
        if len(invoice[field]) == 0:
            invoice[field] = [""] * max_length
        # 如果列表长度不等于最大长度，补充空元素
        elif len(invoice[field]) < max_length:
            invoice[field].extend([""] * (max_length - len(invoice[field])))
    
    # 检查是否存在totalAmount，如果不存在，无法进行后续验证
    if 'totalAmount' not in invoice or not invoice['totalAmount']:
        invoice['totalAmount'] = "0"
    
    # 检查是否存在totalPrice，如果不存在或为空，使用unitPrice作为初始值
    if 'totalPrice' not in invoice or len(invoice['totalPrice']) == 0 or all(not price for price in invoice['totalPrice']):
        invoice['totalPrice'] = invoice['unitPrice'].copy()
    
    # (1) 验证totalPrice的总和是否等于totalAmount
    found_match = False
    try:
        # 安全转换为浮点数
        def safe_float(val):
            try:
                if not val:
                    return 0.0
                return float(val)
            except (ValueError, TypeError):
                return 0.0
        
        total_amount = safe_float(invoice['totalAmount'])
        total_price_sum = sum(safe_float(price) for price in invoice['totalPrice'] if price)
        
        # 如果totalPrice总和不等于totalAmount，尝试其他字段
        if abs(total_price_sum - total_amount) > 0.01:
            # 尝试number求和
            try:
                number_sum = sum(safe_float(num) for num in invoice['number'] if num)
                if abs(number_sum - total_amount) < 0.01:
                    invoice['totalPrice'] = invoice['number'].copy()
                    found_match = True
            except:
                pass
            
            # 尝试unitPrice求和
            if not found_match:
                try:
                    unit_price_sum = sum(safe_float(price) for price in invoice['unitPrice'] if price)
                    if abs(unit_price_sum - total_amount) < 0.01:
                        invoice['totalPrice'] = invoice['unitPrice'].copy()
                        found_match = True
                except:
                    pass
                
            # 尝试taxAmount求和
            if not found_match:
                try:
                    tax_amount_sum = sum(safe_float(tax) for tax in invoice['taxAmount'] if tax)
                    if abs(tax_amount_sum - total_amount) < 0.01:
                        invoice['totalPrice'] = invoice['taxAmount'].copy()
                        found_match = True
                except:
                    pass
                    
            # 如果没有找到匹配项，尝试与totalSmall-totalTax进行匹配
            if not found_match and 'totalSmall' in invoice and invoice['totalSmall'] and 'totalTax' in invoice and invoice['totalTax']:
                try:
                    total_small = safe_float(invoice['totalSmall'])
                    total_tax = safe_float(invoice['totalTax'])
                    calculated_total_amount = round(total_small - total_tax, 2)
                    
                    # 检查totalPrice的总和是否等于totalSmall-totalTax
                    if abs(total_price_sum - calculated_total_amount) < 0.1:
                        # 更新totalAmount为正确的值
                        invoice['totalAmount'] = str(calculated_total_amount)
                        found_match = True
                except:
                    pass
    except Exception as e:
        pass
    
    # (2) 验证taxAmount是否等于totalPrice*taxRate的正负0.01范围（仅验证，不处理）
    for i in range(len(invoice['totalPrice'])):
        try:
            if invoice['totalPrice'][i] and invoice['taxRate'][i] and i < len(invoice['taxAmount']) and invoice['taxAmount'][i]:
                # 安全转换为浮点数
                try:
                    price = float(invoice['totalPrice'][i])
                    # 将百分比转换为小数
                    rate_str = invoice['taxRate'][i].replace('%', '')
                    rate = float(rate_str) / 100
                
                    # 计算税额
                    calculated_tax = round(price * rate, 2)
                    original_tax = float(invoice['taxAmount'][i])
                
                    # 仅验证，不修改原始值
                    if abs(calculated_tax - original_tax) > 0.01:
                        # 记录差异，但不修改原始值
                        field_key = f"taxAmount[{i}]"
                        if "taxAmount_verification" not in modifications:
                            modifications["taxAmount_verification"] = {}
                        modifications["taxAmount_verification"][field_key] = [invoice['taxAmount'][i], str(calculated_tax)]
                        print(f"taxAmount验证：第{i+1}项 原始值={original_tax}，计算值={calculated_tax}，差异={abs(calculated_tax - original_tax)}")
                except (ValueError, TypeError):
                    pass
        except Exception as e:
            pass
    
    # (3) 验证单位unit，不是单位，则置空
    for i in range(len(invoice['unit'])):
        if not isinstance(invoice['unit'][i], str):
            invoice['unit'][i] = ""
        # try:
        #     # 检查是否包含汉字(验证单位unit，如果不是汉字，则置空)
        #     if not any('\u4e00' <= char <= '\u9fff' for char in invoice['unit'][i]) and invoice['unit'][i]:
        #         invoice['unit'][i] = ""
        # except Exception as e:
        #     pass
    
    # 检查unitPrice是否完全等于totalPrice，且number全为1，且unit为空
    all_unit_empty = all(not unit for unit in invoice['unit'])
    all_number_one = all(num == "1" for num in invoice['number'] if num)
    
    # 添加更健壮的数值比较逻辑，防止无效数字格式
    def safe_number_compare(val1, val2):
        try:
            if not val1 or not val2:
                return True  # 如果任一值为空，不进行比较
            
            # 检查是否可以转为浮点数
            num1 = float(val1)
            num2 = float(val2)
            
            # 使用近似比较，处理浮点数精度问题
            return abs(num1 - num2) < 0.01
        except (ValueError, TypeError):
            return False  # 转换失败时返回False
    
    unit_price_equals_total_price = all(
        safe_number_compare(up, tp)
        for up, tp in zip(invoice['unitPrice'], invoice['totalPrice'])
    )
    
    # # 新增功能1：如果unitPrice=totalPrice，且unit或unitPrice为空，则将number置为空
    # for i in range(len(invoice['totalPrice'])):
    #     try:
    #         if invoice['totalPrice'][i] and invoice['unitPrice'][i]:
    #             if safe_number_compare(invoice['totalPrice'][i], invoice['unitPrice'][i]) and (not invoice['unit'][i] or not invoice['unitPrice'][i]):
    #                 invoice['number'][i] = ""
    #     except Exception as e:
    #         pass
    
    # # 新增功能：如果number=totalPrice，且unit或unitPrice为空，则将number置空
    # for i in range(len(invoice['totalPrice'])):
    #     try:
    #         if invoice['totalPrice'][i] and invoice['number'][i]:
    #             if safe_number_compare(invoice['totalPrice'][i], invoice['number'][i]) and (not invoice['unit'][i] or not invoice['unitPrice'][i]):
    #                 print(f"将number置为空：number({invoice['number'][i]})=totalPrice({invoice['totalPrice'][i]})，且unit或unitPrice为空")
    #                 invoice['number'][i] = ""
    #     except Exception as e:
    #         print(f"处理number=totalPrice时出错: {str(e)}")
    #         pass
    
    # if all_unit_empty and all_number_one and unit_price_equals_total_price:
    #     # 将unitPrice和number均置空
    #     invoice['unitPrice'] = [""] * len(invoice['unitPrice'])
    #     invoice['number'] = [""] * len(invoice['number'])
    # else:
    # (4) 验证单价unitPrice和数量number是否匹配totalPrice
    for i in range(len(invoice['totalPrice'])):
        try:
            # 如果number为空，将unitPrice也置为空
            if not invoice['number'][i]:
                # if invoice['unitPrice'][i]:  # 只有当unitPrice不为空时才算修改
                #     invoice['unitPrice'][i] = ""
                pass
            elif invoice['unitPrice'][i] and invoice['number'][i] and invoice['totalPrice'][i]:
                try:
                    # 使用float替代Decimal进行计算
                    unit_price = float(invoice['unitPrice'][i])
                    number = float(invoice['number'][i])
                    total_price = float(invoice['totalPrice'][i])
            
                    # 如果unitPrice*number不等于totalPrice，在原值后添加(随机三个字母)标记，而不是置空
                    calculated_total = round(unit_price * number, 2)
                    if abs(calculated_total - total_price) != 0:  # 不允许误差
                        # 生成三个随机字母
                        import random
                        import string
                        random_letters = ''.join(random.choices(string.ascii_lowercase, k=3))
                        
                        # 在原值后添加括号内的随机字母
                        invoice['unitPrice'][i] = f"{invoice['unitPrice'][i]}({random_letters})"
                        invoice['number'][i] = f"{invoice['number'][i]}({random_letters})"
                        print(f"标记不匹配的值：unitPrice*number={calculated_total}，totalPrice={total_price}，差异={abs(calculated_total - total_price)}")
                except (ValueError, TypeError):
                    # 如果转换失败，在原值后添加(err)标记，而不是置空
                    invoice['unitPrice'][i] = f"{invoice['unitPrice'][i]}(err)"
                    invoice['number'][i] = f"{invoice['number'][i]}(err)"
                    print(f"数值转换失败，已标记为(err)")
        except Exception as e:
            pass
    
    # 新增功能2：如果totalPrice检验符合totalAmount，且totalPrice的最右边包含空元素，则将空元素截断
    try:
        # 计算totalPrice总和
        total_price_sum = sum(safe_float(price) for price in invoice['totalPrice'] if price)
        
        # 检查是否符合totalAmount
        if abs(total_price_sum - safe_float(invoice['totalAmount'])) < 0.01:
            # 找到最后一个非空的totalPrice元素的索引
            last_non_empty_idx = -1
            for i in range(len(invoice['totalPrice'])-1, -1, -1):
                if invoice['totalPrice'][i]:
                    last_non_empty_idx = i
                    break
            
            # 如果找到了最后一个非空元素，且不是最后一个元素，则截断所有字段
            if last_non_empty_idx >= 0 and last_non_empty_idx < len(invoice['totalPrice']) - 1:
                new_length = last_non_empty_idx + 1
                
                # 截断所有列表字段
                for field in list_fields:
                    if len(invoice[field]) > new_length:
                        invoice[field] = invoice[field][:new_length]
                
                print(f"截断所有字段到长度 {new_length}，移除尾部空元素")
    except Exception as e:
        print(f"截断空元素时出错: {str(e)}")
    
    # 将列表转回字符串格式
    for field in list_fields:
        if isinstance(invoice[field], list):
            invoice[field] = str(invoice[field])
    
    # 比较输入和输出，记录有变化的字段
    for field in invoice:
        if field in invoice_data:
            if invoice[field] != invoice_data[field]:
                modifications[field] = [invoice_data[field], invoice[field]]
        else:
            # 新增字段
            modifications[field] = [None, invoice[field]]
    
    # 在所有修改完成后进行分项验证
    try:
        # 将修改后的列表字段转换回Python列表以进行验证
        invoice_lists = {}
        for field in list_fields:
            if isinstance(invoice[field], str) and invoice[field].startswith('[') and invoice[field].endswith(']'):
                cleaned = invoice[field].replace("'", "").replace("[", "").replace("]", "")
                if cleaned:
                    invoice_lists[field] = cleaned.split(', ')
                else:
                    invoice_lists[field] = []
            else:
                invoice_lists[field] = []
        
        # 安全转换为浮点数
        def safe_float_with_default(val, default=0.0):
            try:
                if not val:
                    return default
                return float(val)
            except (ValueError, TypeError):
                return default
        
        # 验证totalPrice与totalAmount的关系
        total_amount = safe_float_with_default(invoice['totalAmount'])
        total_price_sum = sum(safe_float_with_default(price) for price in invoice_lists['totalPrice'] if price)
        total_price_sum = round(total_price_sum, 2)
        
        if abs(total_price_sum - total_amount) < 0.01:
            meetVerifyBaseline = True
            item_verify_result["totalPriceAndTotalAmountVerify"] = True
        
        # 验证taxAmount与totalTax的关系
        tax_amount_sum = 0
        if 'totalTax' in invoice and invoice['totalTax']:
            total_tax = safe_float_with_default(invoice['totalTax'])
            tax_amount_sum = sum(safe_float_with_default(tax) for tax in invoice_lists['taxAmount'] if tax)
            tax_amount_sum = round(tax_amount_sum, 2)
            
            if abs(tax_amount_sum - total_tax) < 0.01:
                item_verify_result["taxAmountAndTotalTaxVerify"] = True
        
        # 验证totalAmount+totalTax与totalSmall的关系
        if 'totalSmall' in invoice and invoice['totalSmall'] and 'totalTax' in invoice and invoice['totalTax']:
            total_small = safe_float_with_default(invoice['totalSmall'])
            total_tax = safe_float_with_default(invoice['totalTax'])
            
            # 检查totalAmount+totalTax是否等于totalSmall
            if abs((total_amount + total_tax) - total_small) < 0.01:
                item_verify_result["totalAmountAndTotalSmallVerify"] = True
                
                # 如果totalAmountAndTotalSmallVerify为true，将totalSmall转为大写赋值给totalBig
                try:
                    chinese_amount = convert_to_chinese_amount(str(total_small))
                    # 无论totalBig是否为空或不等于totalSmall的大写形式，都更新totalBig
                    if 'totalBig' in invoice:
                        modifications['totalBig'] = [invoice['totalBig'], chinese_amount]
                    else:
                        modifications['totalBig'] = [None, chinese_amount]
                    invoice['totalBig'] = chinese_amount
                except Exception as e:
                    print(f"转换金额为大写时出错: {str(e)}")
            
            # 如果totalPrice总和不等于totalAmount，但等于totalSmall-totalTax，也满足基准
            calculated_total_amount = round(total_small - total_tax, 2)
            if abs(total_price_sum - calculated_total_amount) < 0.01 and not item_verify_result["totalPriceAndTotalAmountVerify"]:
                meetVerifyBaseline = True
            
            # 新增第4基准：如果totalPrice总和等于totalAmount，且taxAmount总和等于totalTax，但totalAmount+totalTax不等于totalSmall，
            # 则修正totalSmall为totalAmount+totalTax的值
            if (item_verify_result["totalPriceAndTotalAmountVerify"] and 
                item_verify_result["taxAmountAndTotalTaxVerify"] and 
                not item_verify_result["totalAmountAndTotalSmallVerify"]):
                
                # 计算正确的totalSmall值
                corrected_total_small = round(total_amount + total_tax, 2)
                
                # 记录修改
                if 'totalSmall' in invoice:
                    modifications['totalSmall'] = [invoice['totalSmall'], str(corrected_total_small)]
                else:
                    modifications['totalSmall'] = [None, str(corrected_total_small)]
                
                # 更新totalSmall值
                invoice['totalSmall'] = str(corrected_total_small)
                print(f"应用第4基准：修正totalSmall从{total_small}到{corrected_total_small}（totalAmount({total_amount})+totalTax({total_tax})）")
                
                # 更新验证结果
                item_verify_result["totalAmountAndTotalSmallVerify"] = True
                # 记录原始totalBig
                original_totalBig = invoice['totalBig']
                
                # 更新totalBig
                try:
                    chinese_amount = convert_to_chinese_amount(str(corrected_total_small))
                    # 无论totalBig是否为空或不等于totalSmall的大写形式，都更新totalBig
                    if 'totalBig' in invoice:
                        modifications['totalBig'] = [invoice['totalBig'], chinese_amount]
                    else:
                        modifications['totalBig'] = [None, chinese_amount]
                    invoice['totalBig'] = chinese_amount
                    # 如果original_totalBig包含"整"，则追加上
                    if "整" in original_totalBig and "整" not in invoice['totalBig']:
                        invoice['totalBig'] = invoice['totalBig'] + "整"
                except Exception as e:
                    print(f"转换修正后的金额为大写时出错: {str(e)}")
                
                # 标记已满足基准
                if not meetVerifyBaseline:
                    meetVerifyBaseline = True
                
        # 处理no字段：如果no字段的值与invoiceNumber字段相同或是其子串，则将no字段置为空
        if 'no' in invoice and 'invoiceNumber' in invoice and invoice['no'] and invoice['invoiceNumber']:
            try:
                # 去除可能的空格和其他不可见字符
                no_value = str(invoice['no']).strip()
                invoice_number = str(invoice['invoiceNumber']).strip()
                
                # 检查no是否与invoiceNumber相同或是其子串
                if no_value == invoice_number:
                    invoice['no'] = ""
                    print(f"将no置为空：no({no_value})与invoiceNumber({invoice_number})相同")
                elif no_value in invoice_number:
                    invoice['no'] = ""
                    print(f"将no置为空：no({no_value})是invoiceNumber({invoice_number})的子串")
            except Exception as e:
                print(f"处理no字段时出错: {str(e)}")
    except Exception as e:
        print(f"验证基准条件时出错: {str(e)}")
        pass
    # 根据unit修改model；
    if "model" in invoice:
        origin_model_v = invoice["model"]
        model_corrected_invoice = validate_and_correct_invoice_dict_field_model_unit(invoice)
        cur_model_v = model_corrected_invoice["model"]
        if origin_model_v != cur_model_v:
            modifications["model"] = [origin_model_v, cur_model_v]
            invoice["model"] = cur_model_v
      
    # 修改大小写（金额符合时才替换）
    if "totalBig" in invoice and "totalSmall" in invoice:
        value=safe_float_with_default(invoice["totalAmount"])+safe_float_with_default(invoice["totalTax"])
        if value==safe_float_with_default(invoice["totalSmall"]):
            invoice["totalBig"]=convert_to_chinese_amount(value)
      
    return invoice, modifications, meetVerifyBaseline, item_verify_result

def dict_compare(dict1, dict2):
    """
    比较两个字典，返回键值不同的内容
    
    参数:
        dict1: 第一个字典
        dict2: 第二个字典
    
    返回:
        diff_dict: 包含不同键值的字典，格式为 {key: [dict1_value, dict2_value]}
    """
    diff_dict = {}
    
    # 获取所有键的集合
    all_keys = set(dict1.keys()) | set(dict2.keys())
    
    # 遍历所有键
    for key in all_keys:
        # 情况1：键只存在于dict1中
        if key in dict1 and key not in dict2:
            diff_dict[key] = [dict1[key], None]
        # 情况2：键只存在于dict2中
        elif key not in dict1 and key in dict2:
            diff_dict[key] = [None, dict2[key]]
        # 情况3：键存在于两个字典中，但值不同
        elif key in dict1 and key in dict2 and dict1[key] != dict2[key]:
            diff_dict[key] = [dict1[key], dict2[key]]
    
    return diff_dict

def print_dict(dict_data:dict):
    for key, value in dict_data.items():
        print(f"{key}: {value}")

# def test_right_totalAmount():
#     invoice_list_dict_1=invoice_result_list_dict[0]
#     invoice_list_dict_2=invoice_result_list_dict[2][0]
#     corrected_invoice1, modifications1, meetVerifyBaseline1, item_verify_result1 = validate_and_correct_invoice_dict(invoice_list_dict_1)
#     corrected_invoice2, modifications2, meetVerifyBaseline2, item_verify_result2 = validate_and_correct_invoice_dict(invoice_list_dict_2)
#     # 打印修正后的结果
#     print("修正后的发票数据:")
#     print_dict(corrected_invoice1)
#     print("\n修改记录:")
#     print_dict(modifications1)
#     print("\n分项验证结果:")
#     print_dict(item_verify_result1)
#     print("----------------------meetVerifyBaseline1:", meetVerifyBaseline1)
#     print("--------------------------------")
#     print("修正后的发票数据:")
#     print_dict(corrected_invoice2)
#     print("\n修改记录:")
#     print_dict(modifications2)
#     print("\n分项验证结果:")
#     print_dict(item_verify_result2)
#     print("----------------------meetVerifyBaseline2:", meetVerifyBaseline2)
#     print("--------------------------------两个字典差异结果如下：")
#     diff_dict = dict_compare(corrected_invoice1, corrected_invoice2)
#     print_dict(diff_dict)

def test_right_invoice_data(invoice_data_list):
        # 处理发票数据
    # processed_data = correct_invoice_data( invoice_result_list_dict_complicated)
    # processed_data = correct_invoice_data( invoice_result_list_dict_simple)
    # processed_data = correct_invoice_data( invoice_result_no_diff_list_dict)
    if not invoice_data_list:
        print("输入为空列表，直接返回")
        return invoice_data_list
    processed_data = correct_invoice_data( invoice_data_list)
    print("--------------------------------处理后的发票数据:")
    print(str(processed_data))
    # 打印处理结果
    # print("----------------------meetVerifyBaseline1:", processed_data[3]["invoice1_validation"]["meetVerifyBaseline"])
    # print("----------------------meetVerifyBaseline2:", processed_data[3]["invoice2_validation"]["meetVerifyBaseline"])
    print("--------------------------------两个字典差异结果如下：")
    print_dict(processed_data[2][1])
    print("--------------------------------修正后的第一个发票数据:")
    print_dict(processed_data[0])
    print("--------------------------------修正后的第二个发票数据:")
    print_dict(processed_data[2][0])
    # print("--------------------------------第一个发票的分项验证结果:")
    # print_dict(processed_data[3]["invoice1_validation"]["item_verify_result"])
    # print("--------------------------------第二个发票的分项验证结果:")
    # print_dict(processed_data[3]["invoice2_validation"]["item_verify_result"])
    
    return processed_data

     
def correct_invoice_data(invoice_data_list,add_validation_result=False):
    """
    处理双模型识别后的发票数据列表，对比并合并两个发票字典的信息，返回修正后的结果。
    
    依据函数validate_and_correct_invoice_dict分析处理发票数据列表，返回修正后的结果；
    注意：如果发票数据错误的无法修复（即无法满足基准），则返回原始数据；
    如果输入为空列表，则直接返回空列表。
    
    验证并修正发票处理思路：
    [
        1）数据预处理
        首先深度复制输入数据，避免修改原始数据
        获取第一个发票数据和第二个发票数据
        获取原始第二个字典的差异部分
        
        2）字段预处理和规范化
        处理purchaserName和sellerName字段：
            - 统一左右括号的中英文格式，将中文括号"（）"替换为英文括号"()"
        处理invoiceNumber字段：
            - 如果长度符合标准（8/10/12/20位），优先使用标准长度的值
        处理no字段：
            - 如果一个为空，另一个不为空，且非空值不等于invoiceNumber，则将no置空
            - 如果两个no均非空且相等，且不等于invoiceNumber，则保留该值
            - 如果no字段的值与invoiceNumber字段相同，则将no字段置为空
        处理tradeName字段：
            - 一个包含*，一个不包含，则将包含的赋值给不包含的
            - 如果都包含*，则将字段长度长的赋值给短的
            - 处理中英文括号差异，确保不会因括号类型不同而导致字段被误判为空
        处理unit字段：
            - 如果一个unit全空，另一个里面带有汉字，则将两者均置为全空
        处理remark字段：
            - 去掉\n等特殊符号，统一分号冒号的中英文
            - 选择更长的值作为最终值
        处理其他差异字段：
            - 将差异字典中的值应用到相应字段
        
        3）数据验证与修正
        对两个发票数据分别调用validate_and_correct_invoice_dict进行详细验证和修正
        包括totalPrice验证、taxAmount验证、unit验证、unitPrice和number验证等
        
        4）字段交叉修正
        如果一个字典的验证结果全部为true，则将其关键字段赋值给另一个字典
        以验证通过的字典的列表字段长度为准，截断或填充另一个字典的列表字段
        
        5）数据比较和结果整合
        再次处理purchaserName和sellerName字段，确保括号格式一致
        再次应用model字段处理规则，确保model字段正确
        比较两个修正后的发票数据的差异
        更新processed_data[1]，将在差异字典中存在的键设为false，其他键设为true
        更新处理后的数据结构
        可选地添加验证结果信息
        6)其中一个发票数字验证全对时：
        model字段处理：发票数值结果全对时，则认为其model的长度也对；并进行包含判断，以大包含为准替代另一个值；
        unit,number,unitPrice,totalPrice,taxAmount字段认为全对，赋值给另一个发票数据；
        
    ]
    
    参数:
        invoice_data_list (list): 原始发票数据列表，格式为 [invoice_dict, validation_dict, [invoice_dict_2, differences_dict]]
            - invoice_dict: 第一个发票数据字典
            - validation_dict: 验证字典，标记哪些字段在两个发票字典中相同(true)/不同(false)
            - invoice_dict_2: 第二个发票数据字典
            - differences_dict: 两个发票字典之间的差异字典，格式为 {key: [value1, value2]}
        add_validation_result (bool, optional): 是否在返回结果中添加验证结果信息。默认为False。
    
    返回:
        list: 处理后的发票数据列表，格式与输入相同但内容已修正：
            - 如果add_validation_result=False，返回格式为[invoice_dict_1, validation_dict, [invoice_dict_2, differences_dict]]
            - 如果add_validation_result=True，返回格式为[invoice_dict_1, validation_dict, [invoice_dict_2, differences_dict], validation_result_dict]
                其中validation_result_dict包含：
                - invoice1_validation: 第一个发票的验证结果信息
                - invoice2_validation: 第二个发票的验证结果信息
    """
    # 深度复制输入数据，避免修改原始数据
    import copy
    if not invoice_data_list:
        print("输入为空列表，直接返回")
        return invoice_data_list
    processed_data = copy.deepcopy(invoice_data_list)
    
    # 获取第一个发票数据和第二个发票数据
    invoice_dict_1 = processed_data[0]
    invoice_dict_2 = processed_data[2][0]
    
    # 获取原始第二个字典的差异部分
    ori_diff_dict = processed_data[2][1] if len(processed_data[2]) > 1 else {}
    
    # 记录哪些字段已经被处理过
    processed_fields = set()
    
    # 定义需要处理的列表字段
    list_fields = ['tradeName', 'unit', 'number', 'unitPrice', 'totalPrice', 'taxRate', 'taxAmount']
    
    # 辅助函数：规范化字符串，处理中英文括号差异
    def normalize_string(s):
        if not isinstance(s, str):
            return s
        # 将中文括号替换为英文括号
        return s.replace('（', '(').replace('）', ')')
    
    # 辅助函数：规范化remark字符串
    def normalize_remark(s):
        if not isinstance(s, str):
            return s
        # 去除换行符和多余的空格
        s = s.replace('\n', '').replace('\r', '')
        # 统一中英文标点
        s = s.replace('；', ';').replace('：', ':').replace('，', ',').replace('（', '(').replace('）', ')')
        # 标准化空格
        s = re.sub(r'\s+', ' ', s).strip()
        return s
    
    
    # 处理purchaserName和sellerName字段：统一左右括号的中英文格式
    for field in ['purchaserName', 'sellerName']:
        if field in invoice_dict_1:
            invoice_dict_1[field] = normalize_string(invoice_dict_1[field])
        if field in invoice_dict_2:
            invoice_dict_2[field] = normalize_string(invoice_dict_2[field])
        
        # 如果字段在差异字典中，处理差异字典中的值
        if field in ori_diff_dict and isinstance(ori_diff_dict[field], list) and len(ori_diff_dict[field]) > 1:
            ori_diff_dict[field][1] = normalize_string(ori_diff_dict[field][1])
            # 应用规范化后的值
            invoice_dict_2[field] = ori_diff_dict[field][1]
            processed_fields.add(field)
    
    # 处理invoiceNumber字段：如果长度符合标准（8/10/12/20位），优先使用标准长度的值
    if 'invoiceNumber' in invoice_dict_1 and 'invoiceNumber' in invoice_dict_2:
        invoice_number1 = invoice_dict_1.get('invoiceNumber', '')
        invoice_number2 = invoice_dict_2.get('invoiceNumber', '')
        
        # 检查两个invoiceNumber是否不同且均非空
        if invoice_number1 and invoice_number2 and invoice_number1 != invoice_number2:
            # 去除可能的空格和其他不可见字符
            invoice_number1 = str(invoice_number1).strip()
            invoice_number2 = str(invoice_number2).strip()
            
            # 检查长度是否符合标准位数（20或8或10或12位）
            valid_lengths = [8, 10, 12, 20]
            len1 = len(invoice_number1)
            len2 = len(invoice_number2)
            
            if len1 in valid_lengths and len2 not in valid_lengths:
                # 第一个invoiceNumber长度符合标准，第二个不符合
                invoice_dict_1['invoiceNumber'] = invoice_number1
                
                
                invoice_dict_2['invoiceNumber'] = invoice_number2
                print(f"将invoiceNumber统一为符合标准位数的值: {invoice_number2}（长度为{len2}位）")
                processed_fields.add('invoiceNumber')
    
    # 处理no字段：根据新的规则
    if 'no' in ori_diff_dict and isinstance(ori_diff_dict['no'], list) and len(ori_diff_dict['no']) > 1:
        no1 = invoice_dict_1.get('no', '')
        no2 = ori_diff_dict['no'][1]
        invoice_number = invoice_dict_1.get('invoiceNumber', '') or invoice_dict_2.get('invoiceNumber', '')
        
        # 规则1：如果两个no一个为空一个不为空，且非空值不等于invoiceNumber的值，则将非空的no置为空
        if (not no1 and no2) or (no1 and not no2):
            non_empty_no = no2 if no2 else no1
            # 检查非空值是否等于invoiceNumber
            if non_empty_no != invoice_number:
                # 非空值不等于invoiceNumber，将两个no都置为空
                invoice_dict_1['no'] = ''
                invoice_dict_2['no'] = ''
                print(f"将no置为空：一个为空一个不为空({no1}, {no2})，且非空值({non_empty_no})不等于invoiceNumber({invoice_number})")
        
        # 规则2：如果两个no值均为非空且相等，且不等于invoiceNumber的值，则保留
        elif no1 and no2 and no1 == no2 and no1 != invoice_number:
            # 保留现有值，不做修改
            print(f"保留no值：两个no值均为非空且相等({no1})，且不等于invoiceNumber({invoice_number})")
        
        processed_fields.add('no')
    
    # 处理tradeName字段：一个包含*，一个不包含，则将包含的赋值给不包含的
    if 'tradeName' in ori_diff_dict:
        # 获取原始tradeName值
        tradeName1 = invoice_dict_1.get('tradeName', "['']")
        tradeName2 = ori_diff_dict['tradeName'][1] if isinstance(ori_diff_dict['tradeName'], list) and len(ori_diff_dict['tradeName']) > 1 else "['']"
        
        # 规范化字符串，处理中英文括号差异
        tradeName1 = normalize_string(tradeName1)
        tradeName2 = normalize_string(tradeName2)
        
        # 检查是否为字符串形式的列表，并转换
        if isinstance(tradeName1, str) and tradeName1.startswith('[') and tradeName1.endswith(']'):
            cleaned1 = tradeName1.replace("'", "").replace("[", "").replace("]", "")
            tradeName1_list = cleaned1.split(', ') if cleaned1 else []
        else:
            tradeName1_list = []
            
        if isinstance(tradeName2, str) and tradeName2.startswith('[') and tradeName2.endswith(']'):
            cleaned2 = tradeName2.replace("'", "").replace("[", "").replace("]", "")
            tradeName2_list = cleaned2.split(', ') if cleaned2 else []
        else:
            tradeName2_list = []
        
        # 检查是否包含*
        tradeName1_has_asterisk = any('*' in item for item in tradeName1_list if item)
        tradeName2_has_asterisk = any('*' in item for item in tradeName2_list if item)
        
        # 应用规则：一个包含*，一个不包含，则将包含的赋值给不包含的
        if tradeName1_has_asterisk and not tradeName2_has_asterisk:
            invoice_dict_1['tradeName'] = tradeName1
            invoice_dict_2['tradeName'] = tradeName1
        elif tradeName2_has_asterisk and not tradeName1_has_asterisk:
            invoice_dict_1['tradeName'] = tradeName2
            invoice_dict_2['tradeName'] = tradeName2
        # 如果都包含*，则将字段长度长的赋值给短的
        elif tradeName1_has_asterisk and tradeName2_has_asterisk:
            # 计算总字符长度
            tradeName1_length = sum(len(item) for item in tradeName1_list if item)
            tradeName2_length = sum(len(item) for item in tradeName2_list if item)
            
            if tradeName1_length > tradeName2_length:
                invoice_dict_1['tradeName'] = tradeName1
                invoice_dict_2['tradeName'] = tradeName1
            elif tradeName2_length > tradeName1_length:
                invoice_dict_1['tradeName'] = tradeName2
                invoice_dict_2['tradeName'] = tradeName2
            else:  # 长度相同时，保留两个tradeName不变
                invoice_dict_1['tradeName'] = tradeName1
                invoice_dict_2['tradeName'] = tradeName2
                
        processed_fields.add('tradeName')
    
    # 处理unit字段：如果一个unit全空，另一个里面带有汉字，则将两者均置为全空
    if 'unit' in ori_diff_dict and isinstance(ori_diff_dict['unit'], list) and len(ori_diff_dict['unit']) > 1:
        # 获取原始unit值
        unit1 = invoice_dict_1.get('unit', "['']")
        unit2 = ori_diff_dict['unit'][1] if isinstance(ori_diff_dict['unit'], list) and len(ori_diff_dict['unit']) > 1 else "['']"
        
        # 检查是否为字符串形式的列表，并转换
        if isinstance(unit1, str) and unit1.startswith('[') and unit1.endswith(']'):
            cleaned1 = unit1.replace("'", "").replace("[", "").replace("]", "")
            unit1_list = cleaned1.split(', ') if cleaned1 else []
        else:
            unit1_list = []
            
        if isinstance(unit2, str) and unit2.startswith('[') and unit2.endswith(']'):
            cleaned2 = unit2.replace("'", "").replace("[", "").replace("]", "")
            unit2_list = cleaned2.split(', ') if cleaned2 else []
        else:
            unit2_list = []
        
        # 检查是否全空
        unit1_all_empty = all(not item for item in unit1_list)
        unit2_all_empty = all(not item for item in unit2_list)
        
        # 检查是否包含汉字
        unit1_has_chinese = any(any('\u4e00' <= char <= '\u9fff' for char in item) for item in unit1_list if item)
        unit2_has_chinese = any(any('\u4e00' <= char <= '\u9fff' for char in item) for item in unit2_list if item)
        
        # 应用规则：如果一个unit全空，另一个里面带有汉字，则将两者均置为全空
        if unit1_all_empty and unit2_has_chinese:
            # 第二个unit包含汉字，第一个全空，将第二个也置为全空
            max_len = max(len(unit1_list), len(unit2_list))
            empty_unit = "['']" if max_len <= 1 else "['', " + ", ".join(["''"] * (max_len - 1)) + "]"
            invoice_dict_1['unit'] = empty_unit
            invoice_dict_2['unit'] = empty_unit
            print(f"将unit置为全空：第一个unit全空，第二个unit包含汉字")
        elif unit2_all_empty and unit1_has_chinese:
            # 第一个unit包含汉字，第二个全空，将第一个也置为全空
            max_len = max(len(unit1_list), len(unit2_list))
            empty_unit = "['']" if max_len <= 1 else "['', " + ", ".join(["''"] * (max_len - 1)) + "]"
            invoice_dict_1['unit'] = empty_unit
            invoice_dict_2['unit'] = empty_unit
            print(f"将unit置为全空：第二个unit全空，第一个unit包含汉字")
        
        processed_fields.add('unit')
    
    # 处理remark字段：去掉\n等特殊符号，统一分号冒号的中英文，选择更长的那个值
    if 'remark' in ori_diff_dict:
        # 获取原始remark值
        remark1 = invoice_dict_1.get('remark', "")
        remark2 = ori_diff_dict['remark'][1] if isinstance(ori_diff_dict['remark'], list) and len(ori_diff_dict['remark']) > 1 else ""
        
        # 规范化字符串
        normalized_remark1 = normalize_remark(remark1)
        normalized_remark2 = normalize_remark(remark2)
        
        # 计算长度并选择更长的那个
        if len(normalized_remark1) >= len(normalized_remark2):
            chosen_remark = remark1
        else:
            chosen_remark = remark2
        
        # 将选择的值赋给两个字典
        invoice_dict_1['remark'] = chosen_remark
        invoice_dict_2['remark'] = chosen_remark
        
        processed_fields.add('remark')
    
    # 将其他差异字段的值赋给invoice_dict_2
    for k, v in ori_diff_dict.items():
        if k not in processed_fields and isinstance(v, list) and len(v) > 1:
            invoice_dict_2[k] = v[1]
    
    # 验证并修正两个发票数据
    corrected_invoice1, modifications1, meetVerifyBaseline1, item_verify_result1 = validate_and_correct_invoice_dict(invoice_dict_1)
    corrected_invoice2, modifications2, meetVerifyBaseline2, item_verify_result2 = validate_and_correct_invoice_dict(invoice_dict_2)
    
    # 新增功能：如果一个字典的item_verify_result中所有元素均为true，则将该字典的特定字段赋值给另一个字典
    fields_to_copy = ['unit', 'number', 'unitPrice', 'totalPrice', 'taxRate', 'taxAmount', 'totalSmall', 'totalAmount', 'totalTax', 'totalBig']
    
    # 检查第一个字典的验证结果是否全部为true
    if all(item_verify_result1.values()):
        # model字段处理：发票数值结果全对时，则认为其model的长度也对；并进行包含判断，以大包含为准替代另一个值
        change_field_name='model' 
        if (change_field_name in corrected_invoice1) and (change_field_name in corrected_invoice2):
            corrected_invoice1[change_field_name],corrected_invoice2[change_field_name] = listSafeContainJudgeL1(corrected_invoice1[change_field_name], corrected_invoice2[change_field_name])
        
        print("第一个发票数据验证全部通过，将其关键字段赋值给第二个发票数据")
        for field in fields_to_copy:
            if field in corrected_invoice1:
                corrected_invoice2[field] = corrected_invoice1[field]
        
        # 新增功能：以验证通过的字典的列表字段长度为准，截断另一个字典中多余的元素
        # 首先将所有列表字段转换为Python列表以便处理
        invoice1_lists = {}
        invoice2_lists = {}
        
        for field in list_fields:
            # 处理第一个字典
            if field in corrected_invoice1:
                if isinstance(corrected_invoice1[field], str) and corrected_invoice1[field].startswith('[') and corrected_invoice1[field].endswith(']'):
                    cleaned = corrected_invoice1[field].replace("'", "").replace("[", "").replace("]", "")
                    invoice1_lists[field] = cleaned.split(', ') if cleaned else []
                elif isinstance(corrected_invoice1[field], list):
                    invoice1_lists[field] = corrected_invoice1[field]
                else:
                    invoice1_lists[field] = []
            else:
                invoice1_lists[field] = []
                
            # 处理第二个字典
            if field in corrected_invoice2:
                if isinstance(corrected_invoice2[field], str) and corrected_invoice2[field].startswith('[') and corrected_invoice2[field].endswith(']'):
                    cleaned = corrected_invoice2[field].replace("'", "").replace("[", "").replace("]", "")
                    invoice2_lists[field] = cleaned.split(', ') if cleaned else []
                elif isinstance(corrected_invoice2[field], list):
                    invoice2_lists[field] = corrected_invoice2[field]
                else:
                    invoice2_lists[field] = []
            else:
                invoice2_lists[field] = []
        
        # 找出第一个字典中所有列表字段的最大长度
        max_length = 0
        for field in list_fields:
            if len(invoice1_lists[field]) > max_length:
                max_length = len(invoice1_lists[field])
        
        print(f"以第一个发票数据的列表长度({max_length})为准，截断第二个发票数据中的列表字段")
        
        # 截断或填充第二个字典的列表字段
        for field in list_fields:
            # 如果第二个字典的列表长度超过第一个字典的最大长度，则截断
            if len(invoice2_lists[field]) > max_length:
                invoice2_lists[field] = invoice2_lists[field][:max_length]
                print(f"截断{field}字段从{len(invoice2_lists[field])}到{max_length}")
            # 如果第二个字典的列表长度小于第一个字典的最大长度，则填充空字符串
            elif len(invoice2_lists[field]) < max_length:
                invoice2_lists[field].extend([''] * (max_length - len(invoice2_lists[field])))
                print(f"填充{field}字段从{len(invoice2_lists[field])}到{max_length}")
        
        # 将处理后的列表转回字符串格式并更新第二个字典
        for field in list_fields:
            corrected_invoice2[field] = "['" + "', '".join(invoice2_lists[field]) + "']"
    
    # 检查第二个字典的验证结果是否全部为true
    elif all(item_verify_result2.values()):
        # model字段处理：发票数值结果全对时，则认为其model的长度也对；并进行包含判断，以大包含为准替代另一个值
        change_field_name='model' 
        if (change_field_name in corrected_invoice1) and (change_field_name in corrected_invoice2):
            corrected_invoice1[change_field_name],corrected_invoice2[change_field_name] = listSafeContainJudgeL2(corrected_invoice1[change_field_name], corrected_invoice2[change_field_name])
            
        print("第二个发票数据验证全部通过，将其关键字段赋值给第一个发票数据")
        for field in fields_to_copy:
            if field in corrected_invoice2:
                corrected_invoice1[field] = corrected_invoice2[field]
        
        # 新增功能：以验证通过的字典的列表字段长度为准，截断另一个字典中多余的元素
        # 首先将所有列表字段转换为Python列表以便处理
        invoice1_lists = {}
        invoice2_lists = {}
        
        for field in list_fields:
            # 处理第一个字典
            if field in corrected_invoice1:
                if isinstance(corrected_invoice1[field], str) and corrected_invoice1[field].startswith('[') and corrected_invoice1[field].endswith(']'):
                    cleaned = corrected_invoice1[field].replace("'", "").replace("[", "").replace("]", "")
                    invoice1_lists[field] = cleaned.split(', ') if cleaned else []
                elif isinstance(corrected_invoice1[field], list):
                    invoice1_lists[field] = corrected_invoice1[field]
                else:
                    invoice1_lists[field] = []
            else:
                invoice1_lists[field] = []
                
            # 处理第二个字典
            if field in corrected_invoice2:
                if isinstance(corrected_invoice2[field], str) and corrected_invoice2[field].startswith('[') and corrected_invoice2[field].endswith(']'):
                    cleaned = corrected_invoice2[field].replace("'", "").replace("[", "").replace("]", "")
                    invoice2_lists[field] = cleaned.split(', ') if cleaned else []
                elif isinstance(corrected_invoice2[field], list):
                    invoice2_lists[field] = corrected_invoice2[field]
                else:
                    invoice2_lists[field] = []
            else:
                invoice2_lists[field] = []
        
        # 找出第二个字典中所有列表字段的最大长度
        max_length = 0
        for field in list_fields:
            if len(invoice2_lists[field]) > max_length:
                max_length = len(invoice2_lists[field])
        
        print(f"以第二个发票数据的列表长度({max_length})为准，截断第一个发票数据中的列表字段")
        
        # 截断或填充第一个字典的列表字段
        for field in list_fields:
            # 如果第一个字典的列表长度超过第二个字典的最大长度，则截断
            if len(invoice1_lists[field]) > max_length:
                invoice1_lists[field] = invoice1_lists[field][:max_length]
                print(f"截断{field}字段从{len(invoice1_lists[field])}到{max_length}")
            # 如果第一个字典的列表长度小于第二个字典的最大长度，则填充空字符串
            elif len(invoice1_lists[field]) < max_length:
                invoice1_lists[field].extend([''] * (max_length - len(invoice1_lists[field])))
                print(f"填充{field}字段从{len(invoice1_lists[field])}到{max_length}")
        
        # 将处理后的列表转回字符串格式并更新第一个字典
        for field in list_fields:
            corrected_invoice1[field] = "['" + "', '".join(invoice1_lists[field]) + "']"
    
    # 在validate_and_correct_invoice_dict处理后，再次处理purchaserName和sellerName字段
    # 确保这些字段的括号格式保持一致
    for field in ['purchaserName', 'sellerName']:
        if field in corrected_invoice1:
            corrected_invoice1[field] = normalize_string(corrected_invoice1[field])
        if field in corrected_invoice2:
            corrected_invoice2[field] = normalize_string(corrected_invoice2[field])
            
        # 如果字段在差异字典中，确保应用了规范化后的值
        if field in ori_diff_dict and isinstance(ori_diff_dict[field], list) and len(ori_diff_dict[field]) > 1:
            normalized_value = normalize_string(ori_diff_dict[field][1])
            # 如果规范化后的值与当前值不同，更新当前值
            if corrected_invoice2.get(field) != normalized_value:
                corrected_invoice2[field] = normalized_value
    
    # 比较两个修正后的发票数据的差异
    diff_dict = dict_compare(corrected_invoice1, corrected_invoice2)
    # model的list转str
    if 'model' in corrected_invoice1 and type(corrected_invoice1['model']) == list:
        corrected_invoice1['model'] = str(corrected_invoice1['model'])
    if 'model' in corrected_invoice2 and type(corrected_invoice2['model']) == list:
        corrected_invoice2['model'] = str(corrected_invoice2['model'])
        
    # 更新处理后的数据
    processed_data[0] = corrected_invoice1
    processed_data[2][0] = corrected_invoice2
    
    # 如果differences_dict不存在，创建它
    if len(processed_data[2]) < 2:
        processed_data[2].append(diff_dict)
    else:
        processed_data[2][1] = diff_dict
        
    # 修改 processed_data[1]，将在差异字典中存在的键设为 false，其他键设为 true
    all_keys = set(corrected_invoice1.keys()) | set(corrected_invoice2.keys())
    for key in all_keys:
        processed_data[1][key] = key not in diff_dict
    
    if add_validation_result:
        # 添加验证结果
        processed_data.append({
            "invoice1_validation": {
                "modifications": modifications1,
                "meetVerifyBaseline": meetVerifyBaseline1,
                "item_verify_result": item_verify_result1
            },
            "invoice2_validation": {
                "modifications": modifications2,
                "meetVerifyBaseline": meetVerifyBaseline2,
                "item_verify_result": item_verify_result2
            }
        })
    
    return processed_data


# def test_wrong_invoice_data():
#     # 处理发票数据
#     processed_data = correct_invoice_data(invoice_result_list_wrong_totalAmount_dict)
#     print("--------------------------------处理后的发票数据:")
#     # print(str(processed_data))
#     # 打印处理结果
#     # print("----------------------meetVerifyBaseline1:", processed_data[3]["invoice1_validation"]["meetVerifyBaseline"])
#     # print("----------------------meetVerifyBaseline2:", processed_data[3]["invoice2_validation"]["meetVerifyBaseline"])
#     print("--------------------------------两个字典差异结果如下：")
#     print_dict(processed_data[2][1])
#     print("--------------------------------修正后的第一个发票数据:")
#     print_dict(processed_data[0])
#     print("--------------------------------修正后的第二个发票数据:")
#     print_dict(processed_data[2][0])
#     # print("--------------------------------第一个发票的分项验证结果:")
#     # print_dict(processed_data[3]["invoice1_validation"]["item_verify_result"])
#     # print("--------------------------------第二个发票的分项验证结果:")
#     # print_dict(processed_data[3]["invoice2_validation"]["item_verify_result"])
    
#     return processed_data



# 示例使用
if __name__ == "__main__":
    # 验证并修正发票数据
    test_right_invoice_data(invoice_result_list_dict_simple)
    
    # # 测试单独dict
    # tuple1=validate_and_correct_invoice_dict(invoice_result_dict_1)
    # dict1=tuple1[0]
    # print_dict(dict1)

    # # 测试单位
    # print(is_unit(""))